package com.game;

import com.game.gm.handler.Handler;
import com.game.gm.handler.ResGMmsgHandler;
import com.message.MessagePool;
import game.message.Message;

import java.io.PrintWriter;
import java.net.InetSocketAddress;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class GMClientServer extends ZZClientServer {
	public static final String clientServerConfig = "gmClientServer.xml";
	public static final String serverConfig = "gmServer.xml";
	public static GMClientServer robotClient = null;
	public static int count = 0;
	public IoSession session;
	private int nums;
	public static Object lock = new Object();
	Logger log = Logger.getLogger(GMClientServer.class);

	public GMClientServer(String clientServerConfig, String serverConfig) {
		super(clientServerConfig, serverConfig);
	}

	public static GMClientServer getInstance() {
		if (robotClient == null) {
			String path = GMClientServer.class.getClassLoader().getResource("").getPath();
			synchronized (lock) {
				robotClient = new GMClientServer(path + clientServerConfig, serverConfig);
			}
		}
		return robotClient;
	}

	public void doCommand(IoSession iosession, IoBuffer buf) {
		try {
			int id = buf.getInt();

			Message msg = MessagePool.getInstance().createMessage(id);
			if (msg == null) {
				this.log.info("收到了不存在的消息：" + id);
				return;
			}
			msg.read(buf);
			msg.setSession(iosession);

			Handler handler = (Handler) iosession.getAttribute("handler");
			handler.setMessage(msg);
			handler.setWriter((PrintWriter)(iosession.getAttribute("pw")));
			handler.setCreateTime(System.currentTimeMillis());
			System.out.println("before action.....");
			handler.action();
			iosession.close(true);
		} catch (Exception e) {
			this.log.error(e, e);
		}
	}

	public void exceptionCaught(IoSession arg0, Throwable arg1) {
	}

	public void sessionClosed(IoSession arg0) {
		stop();
		this.log.error("断开");
	}

	public IoSession reconn(IoSession arg0) {
		String ip = arg0.getAttribute("connect-server-ip").toString();
		int port = Integer.parseInt(arg0.getAttribute("connect-server-port").toString());
		ConnectFuture futrue = this.socket.connect(new InetSocketAddress(ip, port));
		futrue.awaitUninterruptibly();
		int tag = Integer.parseInt(arg0.getAttribute("tag").toString());
		IoSession session = futrue.getSession();
		session.setAttribute("tag", Integer.valueOf(tag));
		session.setAttribute("connect-server-ip", ip);
		session.setAttribute("connect-server-port", Integer.valueOf(port));
		session.setAttribute("pw", arg0.getAttribute("pw"));
		session.setAttribute("handler", arg0.getAttribute("handler"));
		return session;
	}

	public void sessionCreate(IoSession arg0) {
	}

	public void sessionIdle(IoSession arg0, IdleStatus arg1) {
	}

	public void sessionOpened(IoSession arg0) {
	}
	
	public IoSession createSession(String tag, PrintWriter writer, ResGMmsgHandler handler){
		ConnectFuture connect = getFutures().get(tag);
		IoSession session = connect.getSession();
	      session.setAttribute("connect-server-id", Integer.valueOf(tag.split("_")[0]));
	      session.setAttribute("connect-server-ip", getServerInfoByTag(tag).getIp());
	      session.setAttribute("connect-server-port", getServerInfoByTag(tag).getPort());
	      session.setAttribute("tag", Integer.valueOf(tag.split("_")[0]));
	      session.setAttribute("pw", writer);
	      session.setAttribute("handler", handler);
	      return session;
	}
	
	public void register(String tag) {
		synchronized (lock) {
			count += 1;
		}
		this.log.error("当前连接数量" + count);
	}
	
//	public void register(IoSession iosession, String tag) {
//		synchronized (lock) {
//			count += 1;
//		}
//		this.log.error("当前连接数量" + count);
//		iosession.setAttribute("tag", Integer.valueOf(Integer.parseInt(tag)));
//		getSessions().put(Integer.valueOf(Integer.parseInt(tag)), iosession);
//	}
	
	protected void stop() {
	}

	public int getNums() {
		return this.nums;
	}

	public void setNums(int nums) {
		this.nums = nums;
	}

//	public ConcurrentHashMap<Integer, IoSession> getSessions() {
//		return this.sessions;
//	}
//
//	public void setSessions(ConcurrentHashMap<Integer, IoSession> sessions) {
//		this.sessions = sessions;
//	}
}